import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/home/task/task_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../server/api/king_api.dart';
import '../../../widgets/base/qkd_text.dart';

class TaskPage extends StatefulWidget {
  const TaskPage({super.key});

  @override
  State<TaskPage> createState() => _TaskPageState();
}

class _TaskPageState extends State<TaskPage> {
  TaskEntity? entity;

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async{
    entity = await KingApi.getTask();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: const Key("task"),
      onVisibilityChanged: (VisibilityInfo info) {
        if(!info.visibleBounds.isEmpty){
          getData();
        }
      },
      child: Scaffold(
        appBar: Styles.appBar(
          backgroundColor: Colours.main, leadingColor: Colours.white),
        backgroundColor: Colours.scaffoldBg,
        body: Stack(
          children: [
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Column(
                children: [
                  Container(
                    height: 120,
                    color: Colours.main,
                  ),
                  Container(
                    height: 60,
                    decoration: const BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colours.main, Colours.scaffoldBg],
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter)),
                  ),
                ],
              )),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: ListView(children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 4),
                    point(),
                    const SizedBox(height: 16),
                    checkIn(),
                    const SizedBox(height: 10),
                    change(),
                    const SizedBox(height: 10),
                    if(entity?.list?.hasValue == true)
                    task()
                  ],
                ),
              ]),
            ),
          ],
        ),
      ),
    );
  }

  Widget point() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        Utils.onEvent("signin_point");
        Get.toNamed(Routes.taskPoints);
      },
      child: Container(
        width: Get.width/2,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const QkdText('我的积分', color: Colours.white, fontSize: 16),
            const SizedBox(height: 2),
            Row(
              children: [
                QkdText(
                  '${entity?.points ?? 0}',
                  color: Colours.white,
                  fontSize: 20,
                  fontWeight: FontWeight.w500
                ),
                const SizedBox(width: 8),
                Image.asset(
                  Utils.getImgPath('arrow_right.png'),
                  width: 6,
                  height: 10,
                  color: Colours.white,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget checkIn() {
    return Styles.card(
      padding: const EdgeInsets.fromLTRB(12, 12, 12, 16),
      child: Column(
        children: [
          Row(
            children: [
              QkdText('连续签到${entity?.signDays ?? 0}天',
                fontSize: 16,
                fontWeight: FontWeight.w500
              ),
              const Spacer(),
              // QkdText('签到提醒')
            ],
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: List.generate(7,
              (index) {
              var sign = 2;
                if((entity?.signDays ?? 0) >= (index+1)){
                  sign = 1;
                }else if(index != 0 && index%2 == 0){
                  sign = 3;
                }
                return Column(
                children: [
                  Image.asset(
                    Utils.getImgPath('check_in_$sign.png'),
                    width: 30,
                  ),
                  Container(height: 6),
                  QkdText('${index + 1}天', fontSize: 12,color: Colours.grey66)
                ],
              );
              },
            ),
          )
        ],
      ));
  }

  Widget change() {
    return GestureDetector(
      onTap: () async{
        Utils.onEvent('signin_point_exchange');
        var result = await Get.toNamed(Routes.pointMarket);
        if(result) getData();
      },
      child: Styles.card(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              Image.asset(
                Utils.getImgPath('task_duihuan.png'),
                width: 40,
              ),
              Container(width: 8),
              const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  QkdText('积分兑换',
                    fontSize: 16,
                    fontWeight: FontWeight.w500
                  ),
                  QkdText('大额优惠等你拿',
                    color: Colours.grey99, fontSize: 12
                  ),
                ],
              ),
              const Spacer(),
              Image.asset(
                Utils.getImgPath('arrow_right.png'),
                width: 6,
                height: 10,
              ),
            ],
          )),
    );
  }

  Widget task() {
    return Styles.card(
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QkdText('做任务赚积分',
            fontSize: 16,
            fontWeight: FontWeight.w500
          ),
          const SizedBox(height: 8),
          ...List.generate(
            entity?.list?.length ?? 0,
            (index) => Padding(
              padding: const EdgeInsets.symmetric(vertical: 12),
              child: Row(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      QkdText(entity?.list?[index].title ?? ""),
                      QkdText(
                        entity?.list?[index].msg ?? "",
                        color: Colours.grey99, fontSize: 12
                      ),
                    ],
                  ),
                  const Spacer(),
                  QkdText(
                    entity?.list?[index].points ?? "",
                    fontSize: 13,color: Colours.goldBD5B00
                  ),
                  const SizedBox(width: 12),
                  if(entity?.list?[index].status == 1)
                  QkdButton(
                    onPressed: () async{
                      var result = await KingApi.receive(entity?.list?[index].type);
                      if(result == 200){
                        getData();
                        ToastUtils.show("领取成功");
                      }
                    },
                    backgroundColor: Colours.main,
                    foregroundColor: Colours.white,
                    width: 56,
                    height: 24,
                    borderRadius: 4,
                    textStyle: const TextStyle(fontSize: 13),
                    text: '领取',
                  ),
                  if(entity?.list?[index].status == 2)
                  QkdButton(
                    onPressed: () {
                      Utils.onEvent('signin_task_go',params: {"task_id":entity?.list?[index].title});
                      if(entity?.list?[index].path.hasValue == true){
                        Utils.doJump(entity!.list![index].path!);
                      }
                    },
                    backgroundColor: Colours.white,
                    foregroundColor: Colours.main,
                    borderSide: const BorderSide(color: Colours.main,width: 1),
                    width: 56,
                    height: 24,
                    borderRadius: 4,
                    textStyle: const TextStyle(fontSize: 13),
                    text: '去完成',
                  ),
                  if(entity?.list?[index].status == 3)
                  QkdButton(
                    onPressed: () {},
                    backgroundColor: Colours.greyF2,
                    foregroundColor: Colours.grey99,
                    width: 56,
                    height: 24,
                    borderRadius: 4,
                    textStyle: const TextStyle(fontSize: 13),
                    text: '已完成',
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
